import React, { useState, useEffect, useMemo, memo } from 'react';
import { Form, Input, Tree } from 'antd';
import PropTypes from 'prop-types';
import menuList from '../../config/menuConfig';

const Item = Form.Item;
const { TreeNode } = Tree;

const AuthForm = memo(({ role }) => {
  const [checkedKeys, setCheckedKeys] = useState([]);

  // 初始化勾选状态（替代 componentWillReceiveProps）
  useEffect(() => {
    const initialMenus = role?.menus || [];
    setCheckedKeys(initialMenus);
  }, [role]);

  // 生成树节点（使用 useMemo 缓存，避免重复渲染）
  const treeNodes = useMemo(() => {
    const generateNodes = (list) => {
      return list.map(item => (
        <TreeNode key={item.key} title={item.title}>
          {item.children && item.children.length > 0 ? generateNodes(item.children) : null}
        </TreeNode>
      ));
    };
    return generateNodes(menuList);
  }, []);

  // 勾选变化回调（优化性能）
  const onCheck = (newCheckedKeys) => {
    setCheckedKeys(newCheckedKeys);
  };

  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 15 },
  };

  return (
    <div>
      <Item label="角色名称" {...formItemLayout}>
        <Input value={role?.name || ''} disabled />
      </Item>
      <Tree
        checkable
        defaultExpandAll
        checkedKeys={checkedKeys}
        onCheck={onCheck}
      >
        <TreeNode title="平台权限" key="all">
          {treeNodes}
        </TreeNode>
      </Tree>
    </div>
  );
});

// 修复 PropTypes 定义（补充类型校验）
AuthForm.propTypes = {
  role: PropTypes.object,
};

export default AuthForm;